<template>
  <div class="container">
    <div class="app-container" style="padding: 20px;" border>
      <el-avatar src="https://img0.baidu.com/it/u=3600954679,641662266&fm=253&app=120&size=w931&n=0&f=JPEG&fmt=auto?sec=1739552400&t=a43ffa3b79b5467b34742959c4bd8558" />
      <el-button type="primary" size="mini" @click="addRole">添加角色</el-button>
      <el-table :data="tableData" style="width: 100%;">
        <el-table-column prop="name" label="角色" width="100">
          <template #default="{row}">
            <span v-if="!row.isEdit">{{ row.name }}</span>
            <!-- 绑定临时数据 临时数据随便你折腾  我有备份 真正的数据在row.name -->
            <el-input v-else v-model="row.temp.name" size="mini" />
          </template>
        </el-table-column>

        <!-- state是1 显示 启用 否则未启用 -->
        <!-- <el-table-column prop="state" label="是否启用" width="100" /> -->
        <el-table-column label="是否启用" width="100">
          <template #default="{row}">
            <span v-if="!row.isEdit">{{ row.state === 1 ? '启用' : '未启用' }}</span>
            <el-switch v-else v-model="row.temp.state" :active-value="1" :inactive-value="0" />
          </template>
        </el-table-column>

        <el-table-column prop="description" label="描述">
          <template #default="{row}">
            <span v-if="!row.isEdit">{{ row.description }}</span>
            <el-input v-else v-model="row.temp.description" type="textarea" size="mini" />
          </template>
        </el-table-column>

        <el-table-column label="操作">
          <!-- 通过默认插槽指定结构 -->
          <!--  -->
          <!-- 文字按钮 -->
          <template #default="{row}">
            <!-- {{ row }} -->
            <!-- obj是这个组件的作者在封装el-table-column组件时，传递给默认插槽的参数 -->
            <div v-if="!row.isEdit">
              <el-button size="mini" type="text" @click="btnPermission(row.id)">分配权限</el-button>
              <el-button type="text" @click="row.isEdit=true">编辑</el-button>
              <el-popconfirm title="确定删除吗？" @onConfirm="del(row.id)">
                <template #reference>
                  <el-button type="text">删除</el-button>
                </template>
              </el-popconfirm>
            </div>
            <div v-else>
              <el-button size="mini" type="primary" @click="saveEdit(row)">确定</el-button>
              <el-button size="mini" @click="cancelEdit(row)">取消</el-button>
            </div>
          </template>
        </el-table-column>
      </el-table>

      <el-pagination
        :current-page="currentPage"
        :page-sizes="[3, 4, 5, 6]"
        :page-size="pagesize"
        layout="total, sizes, prev, pager, next, jumper"
        :total="total"
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
      />

      <!-- 新增角色对话框 -->
      <el-dialog title="新增角色" :visible.sync="showDialog" width="500px" @close="clear">
        <template #title>新增</template>

        <el-form ref="xx" :model="formObj" :rules="rules" label-width="100px" size="mini">
          <el-form-item label="角色名称" prop="name">
            <el-input v-model="formObj.name" />
          </el-form-item>
          <el-form-item label="启用">
            <!-- <el-input></el-input> -->
            <el-switch
              v-model="formObj.state"
              active-color="#13ce66"
              inactive-color="#ff4949"
              :active-value="1"
              :inactive-value="0"
            />
          </el-form-item>
          <el-form-item label="角色描述" prop="description">
            <el-input v-model="formObj.description" type="textarea" />
          </el-form-item>
        </el-form>

        <template #footer>
          <el-button size="mini" type="primary" @click="add">确定</el-button>
          <el-button size="mini" @click="clear">取消</el-button>
        </template>
      </el-dialog>

      <!-- 放置权限弹层 -->
      <el-dialog :visible.sync="showPermissionDialog" title="分配权限">
        <!-- 放置权限数据 -->
        <el-tree
          node-key="id"
          :check-strictly="true"
          :data="permissionData"
          :props="{ label: 'name' }"
          show-checkbox
          default-expand-all
          :default-checked-keys="permIds"
        />
        <el-row slot="footer" type="flex" justify="center">
          <el-col :span="6">
            <el-button type="primary" size="mini" @click="btnPermissionOK">确定</el-button>

            <el-button size="mini" @click="showPermissionDialog = false">取消</el-button>

          </el-col>

        </el-row>
      </el-dialog>

    </div>
  </div>
</template>
<script>
import { getPermissionList } from '@/api/permission'
import { getRoleList, addRole, deleteRole, updateRole, getRoleDetail, assignPerm } from '@/api/role'
import { transLate2TreeData } from '@/utils'
export default {
  name: 'Role',
  data() {
    return {
      tableData: [
      //   {
      //   date: '2016-05-02',
      //   name: '王小虎',
      //   address: '上海市普陀区金沙江路 1518 弄'
      // }, {
      //   date: '2016-05-04',
      //   name: '王小虎',
      //   address: '上海市普陀区金沙江路 1517 弄'
      // }, {
      //   date: '2016-05-01',
      //   name: '王小虎',
      //   address: '上海市普陀区金沙江路 1519 弄'
      // }, {
      //   date: '2016-05-03',
      //   name: '王小虎',
      //   address: '上海市普陀区金沙江路 1516 弄'
      // }
      ],
      total: 0, // 总条数
      pagesize: 5, // 每页显示条数
      currentPage: 1, // 当前页码
      showDialog: false,
      showPermissionDialog: false,
      permissionData: [], // 权限数据
      currentRoleId: null,
      permIds: [],
      formObj: {
        name: '',
        description: '',
        state: '',
        isEdit: false
      },
      rules: {
        name: [
          // 必填校验
          { required: true, message: '请输入角色名称', trigger: 'blur' }
        ],
        description: [
          { required: true, message: '请输入角色描述', trigger: 'blur' }
        ]
      }
    }
  },
  created() {
    this.getRoleList()
  },
  methods: {
    // 点击确定时触发
    async  btnPermissionOK() {
      await assignPerm({
        id: this.currentRoleId,
        permIds: this.$refs.permTree.getCheckedKeys()
      })
      this.$message.success('角色分配权限成功')
      this.showPermissionDialog = false
    },
    async  btnPermission(id) {
      this.currentRoleId = id
      const { permIds } = await getRoleDetail(id)
      this.permIds = permIds
      this.permissionData = transLate2TreeData(await getPermissionList(), 0)
      this.showPermissionDialog = true
    },
    cancelEdit(row) {
      row.temp.name = row.name
      row.temp.description = row.description
      row.isEdit = false
      row.temp.state = row.state
    },
    // 新增编辑方法
    editEdit(row) {
      row.isEdit = true
      // 深度拷贝原始数据
      row.temp = { ...row }
    },
    // 修改后的保存方法示例
    async saveEdit(row) {
      try {
        await updateRole({
          ...row.temp,
          id: row.id
        })
        this.$message.success('修改成功')
        this.getRoleList()
      } catch (error) {
        this.$message.error('保存失败')
      }
    },
    async del(id) {
      await deleteRole(id)
      this.$message.success('删除成功')
      if (this.tableData.length === 1 && this.currentPage !== 1) {
        this.currentPage--
      }
      this.getRoleList()
    },
    async getRoleList() {
      const { rows, total } = await getRoleList(this.currentPage, this.pagesize)
      this.total = total
      this.tableData = rows
      // console.log(rows)
      this.tableData.forEach((item) => {
        this.$set(item, 'isEdit', false)
        this.$set(item, 'temp', {
          name: item.name,
          state: item.state,
          description: item.description
        })
      })
    },
    handleSizeChange(newSize) {
      this.pagesize = newSize
      this.currentPage = 1
      this.getRoleList()
    },
    handleCurrentChange(newPage) {
      this.currentPage = newPage
      this.getRoleList()
    },
    addRole() {
      this.showDialog = true
    },
    add() {
      this.$refs.xx.validate(async(isOk) => {
        if (isOk) {
          await addRole(this.formObj)
          this.$message.success('添加成功')
          this.showDialog = false
          this.$refs.xx.resetFields()
          this.formObj = {
            name: '',
            description: '',
            state: 1
          }
          this.clear()
          this.getRoleList()
        }
      })
    },
    clear() {
      this.showDialog = false
      this.$refs.xx.resetFields()
      this.formObj = {
        name: '',
        description: '',
        state: 1
      }
    }
  }
}
</script>
